## Function to plot the comparison of ACMEs results

plot_AMCEs_comparison <- function(title, data, width = 10, height = 8, scale = 1, base_size = 14) {
  
  k <- length(Attribute_order)
  d <- data
  
  d$Attribute[(d$group == "Difference") & (d$significant == FALSE)] <- "z0"
  d$Attribute[(d$group == "Difference") & (d$significant == TRUE)]  <- "z1"
  
  d$Attribute <- factor(d$Attribute, levels = c(Attribute_order, "z0", "z1"))
  
  if (nrow(filter(d, Attribute == "z0")) == 0) {
    mycolor = c(default_colour_palette[1:k], "black")
  } else if (nrow(filter(d, Attribute == "z1")) == 0) {
    mycolor = c(default_colour_palette[1:k], "lightgrey")
  } else{
    mycolor = default_colour_palette
  }
  
  # ybreaks <- d$order
  # ylabels <- d$ylabels
  
  ybreaks <- d %>% filter(group == "Difference") %>% select(order) %>% pull()
  ylabels <- d %>% filter(group == "Difference") %>% select(ylabels) %>% pull()
  
  g <- ggplot(data = d,
              mapping = aes(y = est,
                            x = order,
                            color = Attribute)) +
    geom_hline(yintercept = 0,
               size = .5,
               colour = "darkgrey",
               linetype = "solid") +
    geom_pointrange(aes(ymin = ymin,
                        ymax = ymax),
                    size = 0.75,
                    fatten = 1.5,
                    na.rm = TRUE) +
    geom_point(data = filter(d, is.na(est) & !is.na(Level) & group != "Difference"),
               size = 1.75,
               mapping = aes(x = order,
                             y = 0),
               na.rm = TRUE) +
    coord_flip(ylim = c(-0.6, 0.6)) +
    scale_y_continuous(breaks = seq(-0.4, 0.4, 0.2),
                       labels = c("", "-20%", "0%", "20%", "")) +
    set_my_ggtheme(base_size = base_size) + # mytheme(10) for PowerPoint
    scale_x_continuous(name = NULL,
                       breaks = ybreaks,
                       labels = ylabels) +
    scale_colour_manual(values = mycolor) +
    ggtitle(title) +
    ylab("Average Marginal Component Effect") +
    facet_grid(~ group)
  
  ggsave(paste0("figures/", title, ".pdf"), 
         plot = g, scale = scale, width = width, height = height)
  
  return(g)
  
}
